import React from 'react'
import { Button, Icon, Input, Table, Tag } from 'antd'
import _ from 'lodash'
import Highlighter from 'react-highlight-words'
import { FormattedMessage } from 'react-intl'
import { convertContent } from '../../../../../constant/lang-util'

export default class ProgramAssignmentsStatusBox extends React.Component {
  state = {
    searchText: '',
  }

  getColumnSearchProps = dataIndex => ({
    filterDropdown: ({setSelectedKeys, selectedKeys, confirm, clearFilters}) => (
      <div style={{padding: 8}}>
        <Input
          ref={node => {
            this.searchInput = node
          }}
          placeholder={`Search ${dataIndex}`}
          value={selectedKeys[0]}
          onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
          onPressEnter={() => this.handleSearch(selectedKeys, confirm)}
          style={{width: 188, marginBottom: 8, display: 'block'}}
        />
        <Button
          type="primary"
          onClick={() => this.handleSearch(selectedKeys, confirm)}
          icon="search"
          size="small"
          style={{width: 90, marginRight: 8}}
        >
          Search
        </Button>
        <Button onClick={() => this.handleReset(clearFilters)} size="small" style={{width: 90}}>
          Reset
        </Button>
      </div>
    ),
    filterIcon: filtered => (
      <Icon type="search" style={{color: '#1890ff'}}/>
    ),
    onFilter: (value, record) =>
      (record[dataIndex] || '')
        .toString()
        .toLowerCase()
        .includes(value.toLowerCase()),
    onFilterDropdownVisibleChange: visible => {
      if (visible) {
        setTimeout(() => this.searchInput.select())
      }
    },
    render: text => (
      <Highlighter
        highlightStyle={{backgroundColor: '#ffc069', padding: 0}}
        searchWords={[this.state.searchText]}
        autoEscape
        textToHighlight={text.toString()}
      />
    ),
  })

  handleSearch = (selectedKeys, confirm) => {
    confirm()
    this.setState({searchText: selectedKeys[0]})
  }

  handleReset = clearFilters => {
    clearFilters()
    this.setState({searchText: ''})
  }
  getCurrentProgress = item => {
    const {isShowAssignmentStatus} = this.props
    const keys = Object.keys(item).filter(key => !(key === 'name' || key === 'tag'))
    if (isShowAssignmentStatus) {
      return keys.length + '/' + keys.filter(key => item[key] !== '未提交' && item[key] !== '已提交').length
    }
    return keys.length + '/' + keys.filter(key => !item[key].includes('未开始计时') && !item[key].includes('未结束计时')).length
  }
  getColumns = data => {
    const taskAssignment = {}
    const colomns = [{
      title: <FormattedMessage id='姓名'/>,
      dataIndex: 'name',
      width: 100,
      key: 'name',
      fixed: 'left'
    }, {
      title: 'Tag',
      dataIndex: 'tag',
      width: 100,
      fixed: 'left',
      ...this.getColumnSearchProps('tag'),
      sorter: (a, b) => a - b < 0,
      render: (item) => {
        return <span>{this.formatTags(item)}</span>
      }
    }, {
      title: <FormattedMessage id='当前进度'/>,
      width: 100,
      fixed: 'left',
      sorter: (a, b) => parseInt(this.getCurrentProgress(a).split('/')[1]) >= this.getCurrentProgress(b).split('/')[1],
      render: (item) => {
        return <div>{this.getCurrentProgress(item)}</div>
      }
    }]
    data.forEach(item => {
      if (!taskAssignment[item['任务卡']]) {
        taskAssignment[item['任务卡']] = new Set()
      }
      taskAssignment[item['任务卡']].add(item['作业'])
    })
    Object.keys(taskAssignment).forEach(task => {
      const taskAssignments = Array.from(taskAssignment[task])
      if (taskAssignment[task]) {
        const assignmentColumns = taskAssignments.map((assignment, index) => ({
          title: assignment, width: 200, dataIndex: assignment, key: task + assignment + index,
          render: (item) => {
            return <div>{this.showStatus(item)}</div>
          }
        }))
        colomns.push({
          title: task,
          children: assignmentColumns
        })
      }
    })

    return colomns
  }
  formatTags = (item) => {
    if (!item) return ''

    const tagColors = item.split(',')

    return tagColors.map((item, index) => {
      const tagColor = item.split('|')
      return <Tag color={tagColor[1]} key={index}>{tagColor[0]}</Tag>
    })
  }
  formatData = data => {
    let formatData = []
    const grouped = _.groupBy(data, item => item['name'])
    Object.keys(grouped).forEach(name => {
      const children = grouped[name]
      let student = {name, tag: grouped[name][0].tag}
      children.forEach(assignment => {
        student[assignment['作业']] = this.getStatus(assignment)
      })
      formatData.push(student)
    })
    return formatData
  }
  getStatus = assignment => {
    const {isShowAssignmentStatus} = this.props
    if (isShowAssignmentStatus) {
      return assignment['已评阅'] ? '已评阅' : assignment['分数']
    }
    if ((assignment.startTime && assignment.startTime === assignment.endTime) || !assignment.endTime) {
      return convertContent('未结束计时')
    }
    if (assignment.startTime && assignment.startTime !== assignment.endTime) {
      return assignment.endTime.replace('T', ' ')
    }
    return convertContent('未开始计时')
  }
  showStatus = item => {
    const {isShowAssignmentStatus} = this.props
    if (isShowAssignmentStatus) {
      item = item || '未提交'
      let color = ''
      if (item === '已提交') color = '#eec130'
      if (item === '未完成') color = 'red'
      if (item === '已完成') color = '#4281f5'
      if (item === '已评阅') color = '#9042f5'

      return <div style={{color, textAlign: 'center'}}>{item}</div>
    }
    return item
  }

  render () {
    const {taskAssignmentStatus} = this.props

    const columns = this.getColumns(taskAssignmentStatus)
    const studentData = this.formatData(taskAssignmentStatus)

    return <div className='assignment-status-box'>
      <Table
        columns={columns}
        dataSource={studentData}
        bordered
        pagination={false}
        size='small'
        scroll={{ x: 'max-content' }}
      />
    </div>
  }
}

